var express = require('express');
var path = require('path');
var fs = require('fs');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port:1314});
var userId = 1;

wss.on('connection',function(ws){
	ws.userId = userId;
	wss.broadcast({
		userId:userId,
		type:'welcome'
	})
	ws.send(JSON.stringify({
		userId:userId,
		type:'assign'
	}))
	userId++;
	ws.on('close',function(){
		wss.broadcast({
			userId:ws.userId,
			type:'leave'
		})		
	})
	ws.on('message',function(data){
		var data = JSON.parse(data);
		wss.broadcast({
			userId:data.userId,
			message:data.message,
			type:'message'
		})
	})
})
wss.broadcast = function(data){
	getRecord(data);
	wss.clients.forEach(function each(client){
		client.send(JSON.stringify(data))
	})
}

//保存聊天记录
function getRecord(data){
	data = JSON.stringify(data)+'\r\n';
	var targetPath = path.resolve('.') + '/public/record/chatRecord.txt';
	fs.appendFile(targetPath,data,(err) => {
		if(err) return;
		console.log("聊天记录已经保存")
	})
}



module.exports = wss;